<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="6">
        <div class="search-container">
          <el-form ref="queryParamsRef" :inline="true" :model="queryParams" class="mb8"
                   label-width="50px">

            <el-form-item>
              <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                              range-separator="截止" start-placeholder="开始日期" type="daterange"
                              style="width: 305px;" value-format="YYYY-MM-DD HH:mm:ss"
                              @change="getList"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <query-form-button @handleQuery="getList" @resetQuery="resetQuery"/>
            </el-form-item>
          </el-form>
        </div>
        <el-table v-adaptive :border="true" :data="drugPurchasingPlanMasterList" :header-cell-style="$headerCellStyle"
                  :stripe="true" highlight-current-row @rowClick="drugPurchasingPlanRowClick">
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="采购申请科室" prop="storageName"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="采购计划单号" width="100px"
                           prop="purchasingPlanNo"/>
          <el-table-column :align="'center'" label="计划生成时间" prop="admissionTime" width="130px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.purchasingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="计划生成人" prop="plannedUserName" width="90px"/>
          <el-table-column :align="'center'" fixed="right" label="药品数量" prop="count" width="65px"/>
          <el-table-column :align="'center'" fixed="right" label="状态" prop="confirmType" width="65px">
            <template #default="scope">
              <span v-if="scope.row.confirmType ==='0'" style="color:#d20303">未确认</span>
              <span v-if="scope.row.confirmType ==='1'" style="color:#023aa4">已确认</span>
              <span v-if="scope.row.confirmType ==='2'" style="color:#027e1d">已采购</span>
              <span v-if="scope.row.confirmType ==='3'" style="color:#a95602">暂存</span>
            </template>
          </el-table-column>
          <el-table-column :align="'right'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作" width="60">
            <template #default="scope">
              <el-tooltip v-if="scope.row.confirmType ==='0'" class="item"
                          content="删除" effect="dark"
                          placement="bottom">
                <el-button circle type="danger" @click="handleDeletePan(scope.row)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                    @pagination="getList"/>
      </el-col>
      <el-col :span="18">
        <el-form ref="formRef" :inline="true" :model="form" :rules="rules">
          <el-empty v-if="form.purchasingPlanNo === undefined" description="请点击左侧采购列表信息"></el-empty>
          <template v-else>
            <el-button class="mb5" style="float: right" type="primary"
                       @click="listDrugPurchasingPlanFun(form.purchasingPlanNo)">
              <template #icon>
                <i-ep-search/>
              </template>
              刷新
            </el-button>
            <el-form-item label="供货单位:" prop="supplier">
              <supplier :id="form.supplier" ref="firmName" :disabled="form.confirmType ==='2'"
                        :placeholder="'请选择供货单位'"
                        style="float: left; width: 150px"
                        @supplierChange="supplierChange"/>
            </el-form-item>
            <el-form-item class="ml20 " label="入库科室:" prop="storageId">
              <drug-storage-dept ref="storageIdDeptRef" :clearable="false" :disabled="true"
                                 :org-id="queryParams.orgId" :value-storage-id="form.storageId"
                                 class="import-master"/>
            </el-form-item>
            <el-form-item label="入库发票号" prop="invoiceNo">
              <el-input v-model="form.invoiceNo"
                        :disabled="!(form.confirmType ==='0' || form.confirmType ==='1'|| form.confirmType ==='3')"
                        clearable style="width: 120px"/>
            </el-form-item>
            <el-form-item>
              <el-button v-if="form.confirmType ==='0' || form.confirmType ==='1'|| form.confirmType ==='3'" plain
                         type="primary"
                         @click="handleAdd">
                <template #icon>
                  <i-ep-plus/>
                </template>
                添加药品
              </el-button>
              <el-button v-if="form.confirmType ==='0' || form.confirmType ==='3'" type="primary" @click="submitForm">
                确认计划
              </el-button>
              <el-button v-if="form.confirmType!='2' "
                         type="success"
                         @click="confirmImport('3')">
                暂存
              </el-button>
              <el-button v-if="form.confirmType==='1'" type="danger"
                         @click="confirmImport('2')">
                <template #icon>
                  <i-ep-FolderOpened/>
                </template>
                提交采购明细
              </el-button>
              <el-button v-if="form.confirmType==='1' || form.confirmType==='2'" type="warning"
                         @click="drugPurchasingPlanPrint">
                <template #icon>
                  <i-ep-printer/>
                </template>
                打印采购计划
              </el-button>
              <el-button type="warning" @click="handleExport"
              >
                <template #icon>
                  <i-ep-download/>
                </template>
                导出
              </el-button>
            </el-form-item>

            <el-table v-adaptive="10" :border="true" :data="form.drugPurchasingPlanList"
                      :expand-row-keys="expandRowKeys"
                      :header-cell-style="$headerCellStyle" :stripe="true" highlight-current-row
                      row-key="drugPurchasingPlanId">
              <el-table-column fixed="left" label="入库明细" type="expand" width="75">
                <template #default="props">
                  <div m="4">
                    <el-table :data="props.row.itemVoList" header-cell-class-name="requiredClass">
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价"
                                       prop="tradePrice"
                                       width="120px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.tradePrice'"
                                        :rules="rules.tradePrice"
                                        class="table-form-margin">
                            <el-input v-model="scope.row.tradePrice" class="table-input"
                                      :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                      @blur="tradePriceBlue(scope.$index,scope.row,props.row,'1')"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="proportion"
                                       width="120px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.proportion'" :rules="rules.proportion"
                                        class="table-form-margin">
                            <el-select ref="ratio" v-model="scope.row.proportion" disabled filterable
                                       placeholder="请选择比例" style="width: 100%"
                                       @change="tradePriceBlue(scope.$index,scope.row,props.row,'1')">
                              <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                                         :label="dict.dictLabel"
                                         :value="dict.dictValue"></el-option>
                            </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价"
                                       prop="retailPrice"
                                       width="120px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.retailPrice'"
                                        :rules="rules.retailPrice"
                                        class="table-form-margin">
                            <el-input v-model="scope.row.retailPrice" class="table-input"
                                      :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                      @blur="tradePriceBlue(scope.$index,scope.row,props.row,'2')"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                                       width="140px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.batchNo'" :rules="rules.batchNo"
                                        class="table-form-margin">
                            <el-input v-model="scope.row.batchNo"
                                      :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                      class="table-input"/>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量" prop="quantity"
                                       width="150px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.quantity'"
                                        class="table-form-margin">
                            <el-input v-model="scope.row.quantity" class="table-input" clearable
                                      :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'">
                              <template #append>
                                <dict-data-tag :options="dictDataMap['spec_unit']"
                                               :value="scope.row.packageUnits"/>
                              </template>
                            </el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期"
                                       prop="produceDate"
                                       width="170px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.produceDate'">
                            <el-date-picker v-model="scope.row.produceDate" :disabled-date="disabledProduceDateFunc"
                                            :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                            class="table-input" clearable
                                            placeholder="生产日期" style="width: 100%" type="date"
                                            value-format="YYYY-MM-DD"
                                            @change="produceDateChange(scope.$index,props.$index)">
                            </el-date-picker>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                                       width="170px">
                        <template #default="scope">
                          <el-form-item :prop="'itemVoList.' + scope.$index + '.expireDate'">
                            <el-date-picker v-model="scope.row.expireDate" class="table-input" clearable
                                            placeholder="有效期" style="width: 100%"
                                            :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                            type="date" value-format="YYYY-MM-DD"
                                            @change="expireDateChange(scope.$index,props.$index)">
                            </el-date-picker>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="货柜" prop="location"
                                       width="120px">
                        <template #default="scope">
                          <el-form-item class="table-form-margin">
                            <el-input v-model="scope.row.location"
                                      :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'"
                                      class="table-input"/>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="追溯码"
                                       prop="trackCodes"
                                       width="85px">
                        <template #default="scope">
                          <el-popover
                            :width="200"
                            placement="left"
                            title="追溯码详情"
                            trigger="hover"
                          >
                            <template #reference>
                              <el-button :disabled="props.row.confirmType =='2' || scope.row.confirmType ==='1'" round
                                         type="warning"
                                         @click="trackCodesEnter(scope.$index,props.$index,scope.row,props.row)">录入
                              </el-button>
                            </template>
                            <template v-if="scope.row.trackCodes">
                              <template v-for="item in scope.row.trackCodes.split(';')">
                                <div style="border-bottom: #9a9a9a 1px dotted">{{ item }}</div>
                              </template>
                              共计录入：<span
                              class="ys-css">{{
                                (scope.row.trackCodes ? scope.row.trackCodes.split(";").length : 0) - 1
                              }}</span>条追溯码
                            </template>
                          </el-popover>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="props.row.confirmType ==='0' || props.row.confirmType ==='1'"
                                       :align="'center'"
                                       class-name="small-padding fixed-width" label="操作"
                                       width="80">
                        <template #default="scope">
                          <el-tooltip class="item" content="删除"
                                      effect="dark"
                                      placement="top">
                            <el-button circle type="danger"
                                       @click="handleDelete(scope.$index,props.$index,scope.row,props.row)">
                              <template #icon>
                                <i-ep-delete/>
                              </template>
                            </el-button>
                          </el-tooltip>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="序号" prop="serialNumber" width="90px">
                <template #default="scope">
                  <!--                  <span class="ys-css" style="font-weight: bold">{{ // scope.$index + 1 }}</span>-->
                  <span class="ys-css" style="font-weight: bold">{{ scope.row.serialNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="药品名称" prop="drugName">
                <template #default="scope">
                  <span class="ys-css" style="font-weight: bold">{{ scope.row.drugName }}</span>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="厂家" prop="firmName">
                <template #default="scope">
                  <span class="ys-css" style="font-weight: bold">{{ scope.row.firmName }}</span>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="packageSpec"
                               width="150px">
                <template #default="scope">
                  <span class="ys-css" style="font-weight: bold">{{ scope.row.packageSpec }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="计划采购数量" width="160">
                <template #default="scope">
                  <el-input v-model="scope.row.purchasingQuantityShow"
                            :disabled="scope.row.confirmType ==='2' || scope.row.confirmType ==='1'"
                            clearable>
                    <template #append>
                      <dict-data-tag :options="dictDataMap['spec_unit']"
                                     :value="scope.row.packageUnits"/>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="计划售价(元)" width="110">
                <template #default="scope">
                  <span class="ys-css" style="font-weight: bold">{{ scope.row.retailPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column :align="'right'" class-name="small-padding fixed-width" header-align="center"
                               label="操作" width="90">
                <template #default="scope">
                  <el-tooltip
                    v-if="scope.row.confirmType ==='0'|| scope.row.confirmType ==='1'|| scope.row.confirmType ==='3'"
                    class="item"
                    content="添加入库明细"
                    effect="dark" placement="bottom">
                    <el-button circle type="primary"
                               @click="addItem(scope.$index,scope.row)">
                      <template #icon>
                        <i-ep-plus/>
                      </template>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip
                    v-if="scope.row.confirmType ==='0' || scope.row.confirmType ==='1'|| scope.row.confirmType ==='3'"
                    class="item"
                    content="删除" effect="dark"
                    placement="bottom">
                    <el-button circle type="danger" @click="handleDeleteMaster(scope.$index,scope.row)">
                      <template #icon>
                        <i-ep-delete/>
                      </template>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-form>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      title="入库药品选择"
      width="500"
    >
      <el-input v-if="isShow" v-model="form.itemName"
                @focus="isShowItemNameFocus()">
      </el-input>
      <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                            :table-head-list="tableHeadList" :title="itemTitle"
                            :width="1000" style="width: 100%"
                            @itemNameInput="itemNameInput" @rowClick="rowClick($event)"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="dialogOk">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
      v-model="trackCodesEnterOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      title=""
      width="400px"
      @close="trackCodesCancel"
    >
      <template #header>
        <div class="ml20 fz15" style="color: #00c0ef;margin-bottom: -20px !important">
          <div>追溯码录入</div>
          <span class="mr20"
                style="font-size: 16px;font-weight: bold;color: #484848">药品名：{{ trackCodesRow.drugName }}</span>
          <div class="mr20"
               style="font-size: 16px;font-weight: bold;color: #484848">厂家：{{ trackCodesRow.firmName }}
          </div>
          <span style="color: #ea0a0a">每条录入完成后,按【回车】输入下一条</span>
        </div>
      </template>
      <el-input
        v-model="trackCodesInput"
        :rows="20"
        placeholder="请输入或扫描追溯码"
        style="width: 100%"
        type="textarea"
        @keydown.enter.native="lineFeed"
      />
      <div>
        共计录入：<span class="ys-css">{{ trackCodesInput ? trackCodesInput.split(";").length - 1 : 0 }}</span>条追溯码
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="trackCodesCancel">取消</el-button>
          <el-button type="primary" @click="trackCodesOk">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {
  addDrugPurchasingPlan,
  delDrugPurchasingPlan,
  delPurchasingPlanNo,
  getDrugPurchasingPlanGroupByPage,
  listDrugPurchasingPlan,
} from "@/api/drug/drugPurchasingPlan.ts"
import {addDrugPurchasingPlanItem} from "@/api/drug/drugPurchasingPlanItem.ts"
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {drugImporOrList, jsonStrInObj} from "@/utils/autoComplete.ts";
import {getAutoDrugPriceInfo} from "@/api/drug/drugImportMaster.ts";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'price_ratio'))
const useUserStore = useUserStoreHook();
const patientList = ref<any>([])
const dialogVisible = ref(false)
const itemAutomatic = ref()
const expandRowKeys = ref<any>([])
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

// 申请采购科室
const storageId = ref();
const storageIdDeptRef = ref()

const {proxy} = getCurrentInstance() as any;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: userInfo.orgId,
  storageId: proxy.$currentSelectDept
  // confirmType: "0"
})

// 追溯码弹出框是否打开
const trackCodesEnterOpen = ref(false);
// 追溯码弹列表数据
const trackCodesRow = ref<any>({});
// 追溯码弹出框input内容
const trackCodesInput = ref<String>("")
// 追溯码点击行号
const currentIndex = ref(-1)
// 追溯码点击的父列号
const currentParentIndex = ref(-1)

// 项目选择自动补全窗体名称
const itemTitle = ref("药品选择");
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(drugImporOrList));
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([]);
// 项目选择自动补全字典数组
const dictArray = ref(["spec_unit"]);

const form = ref<any>({
  drugPurchasingPlanList: []
})
// 总条数
const total = ref(0)


const drugPurchasingPlanMasterList = ref<any>([])


const rules = ref({
  // tradePrice: [{required: true, validator: tradePriceV, trigger: "blur"}],
  // retailPrice: [{required: true, validator: retailPriceV, trigger: "blur"}],
  // produceDate: [{required: true, message: "生产日期不能为空", trigger: "blur"}],
  // expireDate: [{required: true, message: "有效期不能为空", trigger: "blur"}],
  // batchNo: [{required: true, message: "批号不能为空", trigger: "blur"}],
  // importClass: [{required: true, message: "入库方式不能为空", trigger: "change"}],
  // proportion: [{required: true, message: "比例不能为空", trigger: "change"}],
  // storageId: [{required: true, message: "入库科室不能为空", trigger: "blur"}],
  // quantity: [{required: true, validator: quantityNumber, trigger: "blur"}],
});

/** 查询采购入库主信息列表 */
function getList() {
  form.value.drugPurchasingPlanList = []
  getDrugPurchasingPlanGroupByPage(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    drugPurchasingPlanMasterList.value = response.rows.filter(item => item.purchasingPlanNo)
    if (response.rows.length > 0) {
      storageId.value = response.rows[0].storageId
    }
    total.value = response.total;
  });
}

function resetQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/**
 * 主记录行点击事件
 * @param row
 */
function drugPurchasingPlanRowClick(row: any) {
  form.value = row
  listDrugPurchasingPlanFun(row.purchasingPlanNo)
}

/**
 * 查询计划药品列表
 */
function listDrugPurchasingPlanFun(purchasingPlanNo: string) {
  listDrugPurchasingPlan(
    {
      orgId: queryParams.value.orgId,
      purchasingPlanNo: purchasingPlanNo,
    }
  ).then(res => {
    form.value.drugPurchasingPlanList = res.data;
    form.value.confirmType = res.data[0].confirmType
    form.value.supplier = res.data[0].supplier
    form.value.supplierName = res.data[0].supplierName
    form.value.purchasingPlanNo = res.data[0].purchasingPlanNo
    form.value.drugPurchasingPlanList.forEach((item: any) => {
      item.purchasingQuantityShow = item.purchasingQuantity
    //   item.purchasingQuantity = item.purchasingQuantity / item.packageNum
    //   // 设置原始数量，用于区别是否进行修改采购数量
    //   item.primitiveQuantity = item.primitiveQuantity / item.packageNum
    //   // item.itemVoList = []
    })
  })
}

/**
 * 添加入库明细
 * @param index
 * @param row
 */
function addItem(_index: number, row: any) {
  expandRowKeys.value = []
  expandRowKeys.value.push(row.drugPurchasingPlanId)
  if (row.itemVoList.length > 0 && !row.itemVoList[row.itemVoList.length - 1].quantity) {
    return ElMessage.error("请完善数据后再进行添加！")
  }
  // 计算 row.itemVoList 中 quantity 的合计数量
  // const totalQuantity = row.itemVoList.reduce((sum, item) => {
  //   return sum + (Number(item.quantity) || 0);
  // }, 0);
  // if (totalQuantity > row.purchasingQuantity) {
  //   return ElMessage.error("药品【" + row.drugName + "】入库数量不能大于计划数量")
  // }
  row.itemVoList.push(
    {
      expireDate: "",
      proportion: "1",
      drugInfoId: row.drugInfoId,
      drugName: row.drugName,
      drugCode: row.drugCode,
      orgId: row.orgId,
      packageNum: row.packageNum,
      minUnits: row.minUnits,
      packageSpec: row.packageSpec,
      packageUnits: row.packageUnits,
      tradePrice: row.retailPrice,
      retailPrice: row.retailPrice,
      drugPriceId: row.drugPriceId,
      purchasingPlanNo: row.purchasingPlanNo,
      confirmType: '3',
      trackCodes: "",
      drugPurchasingPlanId: row.drugPurchasingPlanId
    }
  )
}

/**
 * 入库记录删除
 * @param index
 * @param propsIndex
 * @param _row
 **/
function handleDeleteMaster(index: number, row: any) {
  ElMessageBox.confirm('确定要删除本条记录吗？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (row.drugPurchasingPlanId) {
      delDrugPurchasingPlan(row.drugPurchasingPlanId).then(() => {
        ElMessage.success("删除成功");
      })
    }
    form.value.drugPurchasingPlanList.splice(index, 1);

  })
}

/**
 * 进价、售价input值改变事件
 * @param _itemIndex
 * @param row 明细本身信息
 * @param parentRow 对应的父级行信息
 * @param type
 */
function tradePriceBlue(_itemIndex: number, row: any, parentRow: any, type: string) {
  if (row.isNationalProcurement === 'Y' && row.tradePrice > parentRow.retailPrice) {
    return ElMessage.error("国采药品零售价不能高于采购设定价格")
  }
  if (row.isNationalProcurement === 'Y' && row.retailPrice > parentRow.retailPrice) {
    return ElMessage.error("国采药品进货价不能高于采购设定价格")
  }
  if (type != '2') {
    row.retailPrice = row.tradePrice * row.proportion
  }
}

/**
 * 入库明细删除
 * @param index
 * @param propsIndex
 * @param _row
 */
function handleDelete(index: number, propsIndex: number, _row: any) {
  ElMessageBox.confirm('确定要删除本条记录吗？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      form.value.drugPurchasingPlanList[propsIndex].itemVoList.splice(index, 1);
      ElMessage.success("删除成功");
    })
}

/** 生产日期校验 */
function disabledProduceDateFunc(time) {
  return time.getTime() > Date.now();
}

/** 生产日期点击事件 */
function produceDateChange(index: number, parentIndex: number) {
  //1095  三年
  const newDate = proxy.$addDay(1095, new Date(form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].produceDate));
  if (newDate) {
    form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].expireDate = proxy.$parseTime(newDate, "{y}-{m}-{d}");
  }
  if (
    proxy.$getDaysDiff(
      form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].expireDate,
      new Date(form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].produceDate)
    ) < 90
  ) {
    return ElMessage.error("药品有效期小于90天。");
  }
}

function expireDateChange(index: number, parentIndex: number) {
  if (
    proxy.$getDaysDiff(
      form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].expireDate,
      new Date(form.value.drugPurchasingPlanList[parentIndex].itemVoList[index].produceDate)
    ) < 90
  ) {
    return ElMessage.error("药品有效期小于90天。");
  }
}


/**
 * 追溯码录入
 * @param row 药品本行数据
 * @param index 药品本行行号
 * @param parentRow 药品主记录行数据
 * @param parentIndex 药品主记录行号
 */
function trackCodesEnter(index: number, parentIndex: number, row: any, _parentRow: any) {
  trackCodesInput.value = row.trackCodes
  trackCodesEnterOpen.value = true
  currentIndex.value = index
  currentParentIndex.value = parentIndex
  trackCodesRow.value = row
}

/**
 * 追溯码录入框关闭
 */
function trackCodesCancel() {
  trackCodesInput.value = ""
  trackCodesEnterOpen.value = false
  currentIndex.value = -1
}

/**
 * 追溯码录入框确定按钮
 */
function trackCodesOk() {
  form.value.drugPurchasingPlanList[currentParentIndex.value].itemVoList[currentIndex.value].trackCodes = trackCodesInput.value
  trackCodesCancel()
}

/**
 * 追溯码录入页面input回车事件
 */
function lineFeed() {
  if (trackCodesInput.value[trackCodesInput.value.length - 1] != ";") {
    trackCodesInput.value += ";"
  }
}


/**
 * 供应商选择事件
 */
function supplierChange(obj) {
  form.value.supplier = obj.id
  form.value.supplierName = obj.supplierName
}

/**
 * 暂存
 */
function temporaryStorageClick() {
  if (!form.value.supplier) {
    return ElMessage.error("请选择供应商")
  }
}

function isSupplierNull() {
  if (!form.value.supplier) {
    return ElMessage.error("请选择供应商")
  }
}

/**
 * 提交采购明细
 * @param confirmType 采购计划确认状态 0：未确认 ，1：已确认，2：已采购，3：暂存
 */
function confirmImport(confirmType: string) {
  if (!form.value.supplier) {
    return ElMessage.error("请选择供应商")
  }
  const message = confirmType === '3' ? '【暂存】' : '【提交采购明细】'
  ElMessageBox.confirm("确认要" + message + "吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let saveData: any = []
      // 合计销售总金额
      let retailPriceSum: number = 0;
      let purchasingQuantityIsZero = false;
      let purchasingQuantityDrugName = "";
      form.value.drugPurchasingPlanList.forEach((parentItem: any) => {
        let i = 1;
        let purchasingQuantity: number = 0;
        parentItem.supplier = form.value.supplier
        parentItem.supplierName = form.value.supplierName
        parentItem.storageId = form.value.storageId
        parentItem.storageName = form.value.storageName
        if (confirmType != '3') {
          parentItem.confirmType = confirmType
        }
        if (!parentItem.drugPurchasingPlanId) {
          parentItem.purchasingPlanNo = form.value.purchasingPlanNo
        }
        if (parentItem.purchasingQuantityShow <= 0) {
          purchasingQuantityDrugName += parentItem.drugName + "、"
          purchasingQuantityIsZero = true
        }
        let itemVoListTemp = parentItem.itemVoList.filter((item: any) => {
          return item.batchNo && item.quantity
        })
        itemVoListTemp.forEach((item: any) => {
          i++;
          item.produceDate = proxy.$parseTime(item.produceDate, "{y}-{m}-{d} {h}:{i}:{s}");
          item.expireDate = proxy.$parseTime(item.expireDate, "{y}-{m}-{d} {h}:{i}:{s}");
          item.itemNo = i;
          item.proportion = "1";
          retailPriceSum += Number((Number(item.retailPrice) * Number(item.quantity)).toFixed(2))
          // 计算采购数量(转化小包装)
          // purchasingQuantity += Number((Number(item.packageNum) * Number(item.quantity)).toFixed(2))
          saveData.push(item)
        })
        // 计算 row.itemVoList 中 quantity 的合计数量
        // const totalQuantity = itemVoListTemp.reduce((sum, item) => {
        //   return sum + (Number(item.quantity) || 0);
        // }, 0);
        // if (totalQuantity > parentItem.purchasingQuantity) {
        //   return ElMessage.error("药品【" + parentItem.drugName + "】入库数量不能大于计划数量")
        // }
        parentItem.purchasingQuantity = Number((Number(parentItem.packageNum) * Number(parentItem.purchasingQuantityShow)).toFixed(2))
        parentItem.itemVoListTemp = itemVoListTemp
      })
      if (purchasingQuantityIsZero) {
        return ElMessage.error("药品【" + purchasingQuantityDrugName.substring(0, purchasingQuantityDrugName.length - 1) + "】采购数量不能小于0")

      }
      if (confirmType != '3' && saveData.length <= 0) {
        ElMessage.error("没有采购药品明细信息，不能保存")
        listDrugPurchasingPlanFun(form.value.purchasingPlanNo)
        return
      }
      const params = {
        orgId: userInfo.orgId,
        drugPurchasingPlanList: form.value.drugPurchasingPlanList,
        purchasingPlanNo: form.value.purchasingPlanNo,
        // 采购计划生成时间
        purchasingTime: form.value.drugPurchasingPlanList[0].purchasingTime,
        supplier: form.value.supplier,
        storageId: storageId.value,
        accountReceivable: retailPriceSum,
        invoiceNo: form.value.invoiceNo,
        isNowInsert: false,
        confirmType: confirmType
      }
      addDrugPurchasingPlanItem(params).then((res: any) => {
        listDrugPurchasingPlanFun(form.value.purchasingPlanNo)
        ElMessage.success("操作成功")
      })
    })
}

function handleClose() {
  dialogVisible.value = false
}

function dialogOk() {
  handleClose()
}

/**
 * 药品新增事件
 */
function handleAdd() {
  dialogVisible.value = true
}


/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  form.value.itemName = event;
  getAutoDrugPriceInfoFun();
}


/** 入库药品检索 */
function getAutoDrugPriceInfoFun() {
  const param = {
    storageId: storageId.value,
    orgId: queryParams.value.orgId,
    itemInfo: form.value.itemName,
  };
  getAutoDrugPriceInfo(param).then((res) => {
    tableBodyList.value = res.data;
    itemAutomatic.value.init();
  });
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);
function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}


/** 药品自动补全点击事件 */
function rowClick(obj) {
  // nextTick(() => {
  if (obj) {
    itemAutomatic.value.closePopover();
    form.value.itemName = ""
    isShow.value = true
    form.value.drugPurchasingPlanList.push(
      {
        priceId: obj.priceId,
        itemInfo: obj.drugName,
        drugInfoId: obj.drugInfoId,
        drugName: obj.drugName,
        drugCode: obj.drugCode,
        orgId: obj.orgId,
        packageSpec: obj.packageSpec,
        currentSpec: obj.currentSpec,
        currentUnits: obj.currentUnits,
        packageUnits: obj.packageUnits,
        units: obj.units,
        tradePrice: obj.tradePrice,
        tradePriceShow: obj.tradePrice,
        retailPriceShow: obj.retailPrice,
        retailPrice: obj.retailPrice,
        packSize: obj.packSize,
        proportion: "1",
        firmId: obj.firmId,
        firmName: obj.firmName,
        packageNum: obj.packageNum,
        purchasingQuantity: 0,
        purchasingQuantityShow: 0,
        drugPriceId: obj.drugPriceId,
        itemVoList: [{"trackCodes": ""}],
        confirmType: form.value.confirmType === '1' ? '1' : '0',
        serialNumber: form.value.drugPurchasingPlanList.length + 1
      }
    )
    tableBodyList.value = [];
    handleClose()
  }
  // });
}

/**
 * 计划确认保存
 */
function submitForm() {
  if (!form.value.supplier) {
    return ElMessage.error("请选择供应商")
  }
  let saveData: any = []
  let purchasingQuantityIsZero = false;
  let purchasingQuantityDrugName = "";

  ElMessageBox.confirm("确认要提交【确认计划】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      form.value.drugPurchasingPlanList.forEach((parentItem: any) => {
        parentItem.purchasingQuantity = parentItem.packageNum * parentItem.purchasingQuantityShow
        parentItem.primitiveQuantity = parentItem.packageNum * parentItem.primitiveQuantity
        parentItem.supplier = form.value.supplier
        parentItem.supplierName = form.value.supplierName

        if (parentItem.purchasingQuantity <= 0) {
          purchasingQuantityDrugName += parentItem.drugName + "、"
          purchasingQuantityIsZero = true
        }
        saveData.push(parentItem)
      })

      if (saveData.length <= 0) {
        return ElMessage.error("没有添加需要采购的药品，不能保存")
      }
      if (purchasingQuantityIsZero) {
        // form.value.drugPurchasingPlanList.forEach((parentItem: any) => {
        //   parentItem.confirmType = '1'
        // })
        return ElMessage.error("药品【" + purchasingQuantityDrugName.substring(0, purchasingQuantityDrugName.length - 1) + "】采购数量不能小于0")

      }
      saveData.forEach(item => {
        item.confirmType = '1'
      })
      const params = {
        orgId: userInfo.orgId,
        downQuantityList: saveData,
        supplier: form.value.supplier,
        storageId: storageId.value,
        purchasingPlanNo: form.value.purchasingPlanNo,
        confirmType: '1',
        isNowInsert: false
      }
      addDrugPurchasingPlan(params).then((res: any) => {
        ElMessage.success("确认保存成功")
        // getList()
        listDrugPurchasingPlanFun(form.value.purchasingPlanNo)
      })
    })
}

getList()

/**
 * 打印采购计划
 */
function drugPurchasingPlanPrint() {
  let url = "/drug/drugPurchasingPlan/drugPurchasingPlanPrint";
  const formData = new FormData()
  formData.append("purchasingPlanNo", form.value.purchasingPlanNo)
  formData.append("orgId", userInfo.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (!res) {
      ElMessage.error('打印采购计划失败')
    }
  })
}

/**
 * 删除采购计划
 * @param row
 */
function handleDeletePan(row: any) {
  ElMessageBox.confirm('是否确认删除？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delPurchasingPlanNo(row.purchasingPlanNo).then(() => {
      getList();
      form.value.purchasingPlanNo = ""
      ElMessage.success("删除成功");
    })
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.$download('/drug/drugPurchasingPlan/export', {
    purchasingPlanNo: form.value.purchasingPlanNo,
    orgId: userInfo.orgId
  }, `药品采购计划${form.value.purchasingPlanNo} + ${proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")}.xlsx`)
}

</script>

<script lang="ts">
export default {
  name: "DrugPurchasingPlanConfirm"
}
</script>

<style scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.table-input .el-input__wrapper) {
  background-color: #ff000017;
}
</style>
